package com.studentms.web;

import com.studentms.bean.Users;
import com.studentms.service.UsersService;
import com.studentms.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

//注解   配置请求路径
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.调取service
        UsersService userService = new UsersServiceImpl();
        Users users = userService.login(username, password);
        //创建获取当前时间
        Date nowDate = new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(nowDate);

        //3.跳转页面
        if(users == null){
            //以弹窗方式提示用户,登录失败

            //1.后台创建cookie
            Cookie cookie = new Cookie("uname",username);
            //2.返回给前端
            resp.addCookie(cookie);
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.println("<script>location.href='login.jsp';alert('用户名或密码不正确');</script>");
        }else{
            //跳转到主页面
            //登录成功
            //session存值
            HttpSession session = req.getSession();
            //保存用户信息
            req.getSession().setAttribute("u1",users);
            req.getSession().setAttribute("format1",format1);
            session.setMaxInactiveInterval(60*30);//单位是秒
            resp.sendRedirect("index.jsp");//重定向
        }

    }
}
